package com.cd.security.handler;

import java.io.IOException;
import java.util.Objects;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cd.common.constant.Constants;
import com.cd.common.constant.LqqConstant;
import com.cd.common.domain.LoginUser;
import com.cd.system.service.impl.UserServiceImpl;
import com.cd.common.util.IpUtils;
import com.cd.common.util.JwtUtils;
import com.cd.common.util.RedisCache;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

/**
 * 自定义退出处理类 返回成功
 *
 * @author
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    private static final Logger logger = LoggerFactory.getLogger(LogoutSuccessHandlerImpl.class);

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserServiceImpl userService;

    /**
     * 退出处理
     *
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        //获取用户名 无法通过SecurityContextHolder.getContext()获取 因为没有进入框架 无法拿到值 会有空指针
        String token = request.getHeader(Constants.AUTHORIZATION);
        if (token == null || !token.startsWith(Constants.TOKEN_PREFIX)) {
            return;
        }
        token=token.split(Constants.TOKEN_PREFIX)[1];
        // 解析token
        String userid;
        try {
            Claims claims = JwtUtils.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            logger.error(LqqConstant.TOKEN_ILLEGAL);
            return;
        }
        String redisKey = LqqConstant.LOGINKEY_PREFIX + userid+"|"+ IpUtils.getIpAddr();
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if (Objects.isNull(loginUser)) {
            // 用户未登录或登录过期 不予处理
            //throw new RuntimeException(LqqConstant.LOGIN_UNAUTHORIZED);
            return;
        }
//        //无法通过该种方式获取
//        LoginUser loginUser =AuthUtils.getLoginUser();
//        String userName = loginUser.getUsername();
//        Long userId = loginUser.getUser().getUserId();


        //清理redis
        redisCache.deleteObject(redisKey);
        //操作记录记录入库
        userService.recordLoginInfo(loginUser.getUser(),LqqConstant.LOGOUT);
        //清理security上下文
        SecurityContextHolder.clearContext();
        //日志输出
        logger.info("{}({})退出了系统",loginUser.getUser().getUserName(),request.getRemoteAddr());




//        LoginUser loginUser = tokenService.getLoginUser(request);
//        if (StringUtils.isNotNull(loginUser)) {
//            String userName = loginUser.getUsername();
//            // 删除用户缓存记录
//            tokenService.delLoginUser(loginUser.getToken());
//            // 记录用户退出日志
//            AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"));
//        }
//        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.success("退出成功")));
    }
}
